﻿using UnityEngine;
using UnityEditor;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {
        [CtxMenuItem("SkinnedMeshRenderer/Skin/Bake to Mesh Renderer",
            "Creates a snapshot of a SkinnedMeshRenderer and stores it in mesh. " +
            "The Skinned Mesh is disable and a Mesh Renderer is created. " +
            "Vertices, normals and tangents are transformed. in world-space. ", 0
            )]
        public static void SkinnedMeshBake()
        {
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<SkinnedMeshRenderer>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;
                if (!SkinnEx.HasMinimumRequirements(context)) continue;

                var smr = context;
                var sharedMesh = SkinnEx.GetSharedMesh(smr);
                if (!sharedMesh) continue;

                var smrName = SkinnEx.EnforceObjectName(smr);
                var maxWeight = 0f;
                var shapeIndex = 0;
                var totalWeights = 0;

                for (int i = 0; i < sharedMesh.blendShapeCount; i++)
                {
                    float shapeWeight = smr.GetBlendShapeWeight(i);
                    if (shapeWeight > 0f) totalWeights++;
                    if (shapeWeight > maxWeight) { maxWeight = shapeWeight; shapeIndex = i; }
                }

                string bsname = totalWeights == 1 && maxWeight == 100f ? sharedMesh.GetBlendShapeName(shapeIndex) : smrName;
                if (bsname != smrName)
                {
                    int dialog = EditorUtility.DisplayDialogComplex("Bake to Mesh Filter", "Blend-shapes used!: would you like to name the new mesh \"" + bsname + "\"?", "Yes", "No", "Cancel");
                    switch (dialog)
                    {
                        case 0: break;
                        case 1: bsname = smrName; break;
                        case 2: return;
                    }
                }

                var mf = smr.BakeToMeshFilter(true);
                if (!mf) continue;
                mf.gameObject.name = bsname;
                Undo.RegisterCreatedObjectUndo(mf.gameObject, "Bake World");
                Selection.objects = new Object[] { mf.gameObject };
                Undo.RegisterCompleteObjectUndo(context, "Bake World");
                //context.gameObject.SetActive(false);
            }

            SkinnContext.Finished();
        }
    }
}